#include "kernel_operator.h"

constexpr int32_t TOTAL_LENGTH = 8 * 2048;                            // total length of data
constexpr int32_t USE_CORE_NUM = 8;                                   // num of core used
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;         // length computed of each core
constexpr int32_t TILE_NUM = 8;                                       // split data into 8 tiles for each core
constexpr int32_t BUFFER_NUM = 2;                                     // tensor num for each queue
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM; // separate to 2 parts, due to double buffer

class KernelLogit {
public:
    __aicore__ inline KernelLogit() {}
    __aicore__ inline void Init(GM_ADDR x,  GM_ADDR z)
    {
        xGm.SetGlobalBuffer((__gm__ half *)x + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        zGm.SetGlobalBuffer((__gm__ half *)z + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, TILE_LENGTH * sizeof(half));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, TILE_LENGTH * sizeof(half));
        pipe.InitBuffer(tmpBuf0, TILE_LENGTH * sizeof(half));
        pipe.InitBuffer(tmpBuf1, TILE_LENGTH * sizeof(half));
        pipe.InitBuffer(tmpBuf2, TILE_LENGTH * sizeof(half));
        pipe.InitBuffer(tmpBuf3, TILE_LENGTH * sizeof(half));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.AllocTensor<half>();
        AscendC::DataCopy(xLocal, xGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueX.EnQue(xLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.DeQue<half>();
        AscendC::LocalTensor<half> zLocal = outQueueZ.AllocTensor<half>();
        AscendC::LocalTensor<half> tmp0 = tmpBuf0.Get<half>();
        AscendC::LocalTensor<half> tmp1 = tmpBuf1.Get<half>();
        AscendC::LocalTensor<half> tmp2 = tmpBuf2.Get<half>();
        AscendC::LocalTensor<half> tmp3 = tmpBuf3.Get<half>();

        // 数值保护常数
        const half eps = (half)(6.1e-5);      // 接近 half 精度极限，但避免下溢
        const half one_minus_eps = (half)(1.0 - 6.1e-5);
        
        // 步骤1: 输入范围保护，防止数值不稳定
        AscendC::Duplicate(tmp0, eps, TILE_LENGTH);
        AscendC::Max(tmp1, xLocal, tmp0, TILE_LENGTH);           // max(x, eps)
        
        AscendC::Duplicate(tmp0, one_minus_eps, TILE_LENGTH);
        AscendC::Min(tmp2, tmp1, tmp0, TILE_LENGTH);             // min(max(x, eps), 1-eps)
        // z = ln( x / ( 1 − x ) ) = - ln( 1/x - 1 )

        // 步骤2: 使用更精确的logit计算方法
        // 对于中等值使用 logit(x) = ln(x) - ln(1-x)

        // ln(x_clipped)
        AscendC::Ln(tmp0, tmp2, TILE_LENGTH);
        
        // 1 - x_clipped
        AscendC::Duplicate(tmp1, (half)(1.0), TILE_LENGTH);
        AscendC::Sub(tmp1, tmp1, tmp2, TILE_LENGTH);
        
        // ln(1 - x_clipped)
        AscendC::Ln(tmp3, tmp1, TILE_LENGTH);
        
        // ln(x) - ln(1-x)
        AscendC::Sub(zLocal, tmp0, tmp3, TILE_LENGTH);

        outQueueZ.EnQue<half>(zLocal);
        inQueueX.FreeTensor(xLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<half> zLocal = outQueueZ.DeQue<half>();
        AscendC::DataCopy(zGm[progress * TILE_LENGTH], zLocal, TILE_LENGTH);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuf0, tmpBuf1, tmpBuf2, tmpBuf3;
    AscendC::GlobalTensor<half> xGm;
    AscendC::GlobalTensor<half> zGm;
};

extern "C" __global__ __aicore__ void logit_custom(GM_ADDR x, GM_ADDR z)
{
    KernelLogit op;
    op.Init(x, z);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void logit_custom_do(uint32_t blockDim, void *stream, uint8_t *x, uint8_t *z)
{
    logit_custom<<<blockDim, nullptr, stream>>>(x, z);
}
#endif
